﻿using System.Collections.ObjectModel;
using System.Windows;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using IMClient.Cache.Repositories;
using IMClient.Model;
using IMClient.Model.Message;
using IMClient.Model.UI;
using IMClient.WebSocketService;

namespace IMClient.ViewModels;

public partial class ChatPageViewModel : ObservableObject
{
    [ObservableProperty]
    private ChatParticipantViewModel? selectedParticipant;  // 可以是好友或群聊

    [ObservableProperty]
    private ObservableCollection<ChatParticipantViewModel> chatParticipants = new();  // 包含好友和群聊

    [ObservableProperty]
    private ObservableCollection<ChatParticipantViewModel> filteredParticipants;

    [ObservableProperty]
    private ObservableCollection<ChatMessage> chatHistory = new();

    [ObservableProperty]
    private string searchContent = "";

    [ObservableProperty]
    private string newMessage = "";

    private readonly ChatHistoryRepository _chatHistoryRepository;
    private readonly ChatRecordRepository _chatRecordRepository;

    // 添加新的事件
    public event EventHandler? ScrollToBottomRequested;

    public ChatPageViewModel()
    {
        _chatHistoryRepository = new ChatHistoryRepository();
        _chatRecordRepository = new ChatRecordRepository();
        WebSocketConnection.OnMessageReceived += OnMessageReceived;
        GroupCreatorManagerViewModel.GroupAvatarUpdated += OnGroupAvatarUpdated;
        GroupCreatorManagerViewModel.GroupNameUpdated += OnGroupNameUpdated;

        GroupNotificationViewModel.GroupAvatarUpdated += OnGroupAvatarUpdated;
        GroupNotificationViewModel.GroupNameUpdated += OnGroupNameUpdated;

        ContactsPageViewModel.ParticipantAdded+= OnParticipantAdded;
        FilteredParticipants = new ObservableCollection<ChatParticipantViewModel>();
        FilterParticipants(string.Empty);
        LoadChatRecordsFromDatabaseAsync();
    }

    // 更新聊天记录，当选中的聊天对象变化时自动切换聊天记录
    partial void OnSelectedParticipantChanged(ChatParticipantViewModel? value)
    {
        if (value != null)
        {
            UpdateSelectedParticipant(value);
        }
    }

    private async void UpdateSelectedParticipant(ChatParticipantViewModel participant)
    {
        SelectedParticipant = participant;

        if (participant is FriendViewModel friend)
        {
            // 处理好友聊天记录
            var messages = await _chatHistoryRepository.GetChatMessagesAsync(User.UserId ?? string.Empty, friend.Id, limit: 30);
            var chatHistorys = new ObservableCollection<ChatMessage>();
            foreach (var message in messages)
            {
                if (message.SenderId == User.UserId&&message.IsSentByUser)
                {
                    message.IsSentByUser = true;
                    chatHistorys.Add(message);
                }
                else if (message.SenderId != User.UserId && !message.IsSentByUser)
                {
                    message.IsSentByUser = false;
                    chatHistorys.Add(message);
                }
                
            }
            ChatHistory = new ObservableCollection<ChatMessage>(chatHistorys);
        }
        else if (participant is GroupViewModel group)
        {
            // 处理群聊聊天记录
            var messages = await _chatHistoryRepository.GetGroupChatMessagesAsync(User.UserId ?? string.Empty, group.Id, limit: 30);
            ChatHistory = new ObservableCollection<ChatMessage>(messages);
        }

        // 清空未读消息计数
        participant.UnreadCount = 0;
        
        ScrollToBottomRequested?.Invoke(this, EventArgs.Empty);
    }

    [RelayCommand]
    private async Task SendMessage()
    {
        if (string.IsNullOrWhiteSpace(NewMessage) || SelectedParticipant == null)
            return;

        ChatMessage chatMessage;
        string participantId = SelectedParticipant is FriendViewModel ? SelectedParticipant.Id : ((GroupViewModel)SelectedParticipant).Id;

        if (SelectedParticipant is FriendViewModel friend)
        {
            chatMessage = new ChatMessage
            {
                SenderId = User.UserId,
                SenderName = User.UserName ?? string.Empty,
                SenderAvatar = User.UserAvatar ?? string.Empty,
                Content = NewMessage,
                ChatType = "private",
                ContentType = "text",
                Timestamp = DateTime.UtcNow,
                IsSentByUser = true,
                ReceiverId = participantId
            };
            ChatHistory.Add(chatMessage);
            ScrollToBottomRequested?.Invoke(this, EventArgs.Empty);

            await _chatHistoryRepository.SaveChatMessageAsync(User.UserId, chatMessage);

            friend.LastMessage = NewMessage;
            friend.LastMessageTime = chatMessage.Timestamp.ToLocalTime().ToString("HH:mm");

            await WebSocketConnection.SendMessage(chatMessage);
            await _chatRecordRepository.SaveChatRecordAsync(chatMessage, SelectedParticipant, User.UserId ?? string.Empty);
        }
        else if (SelectedParticipant is GroupViewModel group)
        {
            GroupChatMessage groupMessage = new GroupChatMessage
            {
                SenderId = User.UserId,
                SenderName = User.UserName ?? string.Empty,
                SenderAvatar = User.UserAvatar ?? string.Empty,
                Content = NewMessage,
                ChatType = "group",
                ContentType = "text",
                Timestamp = DateTime.UtcNow,
                IsSentByUser = true,
                GroupId = group.Id,
                GroupAvatar = group.Avatar,
                GroupName = group.Name,
            };
            ChatHistory.Add(groupMessage);
            ScrollToBottomRequested?.Invoke(this, EventArgs.Empty);

            await _chatHistoryRepository.SaveGroupChatMessageAsync(User.UserId, groupMessage);
            group.LastMessage = NewMessage;
            group.LastMessageTime = groupMessage.Timestamp.ToLocalTime().ToString("HH:mm");
            await WebSocketConnection.SendMessage(groupMessage);

            await _chatRecordRepository.SaveChatRecordAsync(groupMessage, SelectedParticipant, User.UserId);
        }
        else
        {
            throw new InvalidOperationException("Unknown participant type");
        }
        NewMessage = string.Empty;
    }


    public void FilterParticipants(string keyword)
    {
        FilteredParticipants.Clear();

        var filtered = ChatParticipants
            .Where(participant => string.IsNullOrEmpty(keyword) || participant.Name.Contains(keyword, StringComparison.OrdinalIgnoreCase))
            .ToList();

        foreach (var participant in filtered)
        {
            FilteredParticipants.Add(participant);
        }
    }

    partial void OnSearchContentChanged(string value)
    {
        FilterParticipants(value);
    }

    private async void LoadChatRecordsFromDatabaseAsync()
    {
        if (string.IsNullOrEmpty(User.UserId))
            return;

        var chatRecords = await _chatRecordRepository.GetChatRecordsByUserIdAsync(User.UserId);

        ChatParticipants.Clear();
        foreach (var record in chatRecords)
        {
            if (record is FriendViewModel friend)
            {
                ChatParticipants.Add(friend);
            }
            else if (record is GroupViewModel group)
            {
                ChatParticipants.Add(group);
            }
        }

        FilterParticipants(string.Empty);
    }


    private void OnMessageReceived(BaseMessage message)
    {
        Application.Current.Dispatcher.BeginInvoke(async () =>
        {
            if (message is ChatMessage chatMessage)
            {
                if (message.SenderId == User.UserId)
                    return;
                // 根据 ChatType 判断是私聊还是群聊
                var isPrivateChat = chatMessage.ChatType == "private";

                string? groupId = null;
                string? groupAvatar = null;
                string? groupName = null;

                if (!isPrivateChat && message is GroupChatMessage groupChatMessage)
                {
                    groupId = groupChatMessage.GroupId;
                    groupAvatar= groupChatMessage.GroupAvatar;
                    groupName=groupChatMessage.GroupName;
                    await _chatHistoryRepository.SaveGroupChatMessageAsync(User.UserId, groupChatMessage);
                }

                if (isPrivateChat)
                {
                    chatMessage.IsSentByUser = false;
                    await _chatHistoryRepository.SaveChatMessageAsync(User.UserId ?? string.Empty, chatMessage);
                }


                // 找到对应的聊天参与者
                var participant = isPrivateChat
                    ? ChatParticipants.FirstOrDefault(p => p is FriendViewModel f && f.Id == chatMessage.SenderId)
                    : ChatParticipants.FirstOrDefault(p => p is GroupViewModel g && g.Id == groupId);

                if (participant != null)
                {
                    if(SelectedParticipant == participant)
                    {
                        ChatHistory.Add(chatMessage);
                        ScrollToBottomRequested?.Invoke(this, EventArgs.Empty);
                    }

                    // 更新最后一条消息
                    if (participant is FriendViewModel friend)
                    {
                        friend.LastMessage = chatMessage.Content;
                        friend.LastMessageTime = chatMessage.Timestamp.ToLocalTime().ToString("HH:mm");
                        if(SelectedParticipant!=participant)
                            friend.UnreadCount++;
                    }
                    else if (participant is GroupViewModel group)
                    {
                        group.LastMessage = chatMessage.Content;
                        group.LastMessageTime = chatMessage.Timestamp.ToLocalTime().ToString("HH:mm");
                        if(SelectedParticipant!=participant)
                            group.UnreadCount++;
                    }

                    await _chatRecordRepository.SaveChatRecordAsync(chatMessage, participant, User.UserId ?? string.Empty);
                }
                else
                {
                    // 如果找不到对应的聊天参与者，新增参与者
                    if (isPrivateChat)
                    {
                        var friend = new FriendViewModel
                        {
                            Id = chatMessage.SenderId,
                            Name = chatMessage.SenderName,
                            Avatar = chatMessage.SenderAvatar ?? string.Empty,
                            LastMessage = chatMessage.Content,
                            LastMessageTime = chatMessage.Timestamp.ToLocalTime().ToString("HH:mm"),
                            UnreadCount = 1
                        };
                        ChatParticipants.Add(friend);
                        FilterParticipants(SearchContent);
                    }
                    else
                    {
                        var group = new GroupViewModel
                        {
                            Id = groupId!,
                            Avatar= groupAvatar!,
                            Name = groupName!,
                            LastMessage = chatMessage.Content,
                            LastMessageTime = chatMessage.Timestamp.ToLocalTime().ToString("HH:mm"),
                            UnreadCount = 1
                        };
                        ChatParticipants.Add(group);
                        FilterParticipants(SearchContent);
                    }
                    await _chatRecordRepository.SaveChatRecordAsync(chatMessage, participant!, User.UserId ?? string.Empty);
                }
            }
        });
    }
    private void OnGroupAvatarUpdated(string groupId, string newAvatar)
    {
        Application.Current.Dispatcher.Invoke(() =>
        {
            // 查找对应的群
            var group = ChatParticipants.OfType<GroupViewModel>().FirstOrDefault(g => g.Id == groupId);
            if (group != null)
            {
                group.Avatar = newAvatar; // 更新头像
                FilterParticipants(string.Empty);
            }
        });
    }
    public void OnGroupNameUpdated(string groupId, string newName)
    {
        Application.Current.Dispatcher.Invoke(() =>
        {
            // 查找对应的群
            var group = ChatParticipants.OfType<GroupViewModel>().FirstOrDefault(g => g.Id == groupId);
            if (group != null)
            {
                group.Name = newName; // 更新头像
                FilterParticipants(string.Empty);
            }
        });
    }

    public async void OnParticipantAdded(ChatParticipantViewModel chatParticipantViewModel)
    {
        ChatParticipants.Add(chatParticipantViewModel);
        ChatMessage chatMessage = new ChatMessage()
        {
            SenderId = chatParticipantViewModel.Id,
            SenderName = chatParticipantViewModel.Name ?? string.Empty,
            SenderAvatar = chatParticipantViewModel.Avatar ?? string.Empty,
            Content = string.Empty,
            ChatType = "private",
            ContentType = "text",
            Timestamp = DateTime.UtcNow,
            IsSentByUser = false,
            ReceiverId = User.UserId
        };
        await _chatRecordRepository.SaveChatRecordAsync(chatMessage, chatParticipantViewModel, User.UserId);
        FilterParticipants(SearchContent);
    }

}